package com.example.project.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.example.project.entity.IssueNotification;
import com.example.project.mapper.IssueNotificationMapper;
import com.example.project.service.IssueNotificationService;

/**
 * 需求通知服务实现类
 */
@Service
public class IssueNotificationServiceImpl implements IssueNotificationService {
    
    @Autowired
    private IssueNotificationMapper notificationMapper;
    
    // 以下是实现接口方法
    
    @Override
    public IssueNotification selectIssueNotificationById(Long id) {
        return notificationMapper.selectById(id);
    }
    
    @Override
    public List<IssueNotification> selectIssueNotificationList(IssueNotification issueNotification) {
        // 根据条件查询通知列表
        Map<String, Object> conditions = new HashMap<>();
        return notificationMapper.findByConditions(conditions);
    }
    
    @Override
    public int selectUnreadCountByUserId(Long userId) {
        return notificationMapper.countUnreadNotificationsByUserId(userId);
    }
    
    @Override
    public List<IssueNotification> selectNotificationsByUserId(Long userId, Integer limit) {
        if (limit != null && limit > 0) {
            return notificationMapper.getLatestNotificationsByUserId(userId, limit);
        } else {
            return notificationMapper.getNotificationsByUserId(userId);
        }
    }
    
    @Override
    @Transactional
    public int insertIssueNotification(IssueNotification issueNotification) {
        issueNotification.setCreateTime(LocalDateTime.now());
        issueNotification.setIsRead(0);
        return notificationMapper.insert(issueNotification);
    }
    
    @Override
    @Transactional
    public int updateIssueNotification(IssueNotification issueNotification) {
        return notificationMapper.updateById(issueNotification);
    }
    
    @Override
    @Transactional
    public int deleteIssueNotificationByIds(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += deleteIssueNotificationById(id);
        }
        return count;
    }
    
    @Override
    @Transactional
    public int deleteIssueNotificationById(Long id) {
        return notificationMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public int markAsRead(Long id) {
        IssueNotification notification = new IssueNotification();
        notification.setId(id);
        notification.setIsRead(1);
        notification.setReadTime(LocalDateTime.now());
        return notificationMapper.updateById(notification);
    }
    
    @Override
    @Transactional
    public int markAsReadBatch(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += markAsRead(id);
        }
        return count;
    }
    
    @Override
    @Transactional
    public boolean sendCommentNotification(Long issueId, Long commenterId, String commentContent, List<Long> receiverIds) {
        if (CollectionUtils.isEmpty(receiverIds)) {
            return true;
        }
        
        List<IssueNotification> notifications = new ArrayList<>();
        String truncatedContent = commentContent.length() > 100 ? commentContent.substring(0, 100) + "..." : commentContent;
        
        for (Long userId : receiverIds) {
            IssueNotification notification = new IssueNotification();
            notification.setIssueId(issueId);
            notification.setReceiverId(userId);
            notification.setNotificationType(1); // 1-评论
            notification.setTitle("需求有新评论");
            notification.setContent(truncatedContent);
            notification.setSenderId(commenterId);
            
            notifications.add(notification);
        }
        
        // 批量插入通知
        return notificationMapper.batchInsert(notifications) > 0;
    }
    
    @Override
    @Transactional
    public boolean sendStatusChangeNotification(Long issueId, Long operatorId, String statusFrom, String statusTo, List<Long> receiverIds) {
        if (CollectionUtils.isEmpty(receiverIds)) {
            return true;
        }
        
        List<IssueNotification> notifications = new ArrayList<>();
        String content = "需求状态已从" + statusFrom + "变更为" + statusTo;
        
        for (Long userId : receiverIds) {
            IssueNotification notification = new IssueNotification();
            notification.setIssueId(issueId);
            notification.setReceiverId(userId);
            notification.setNotificationType(2); // 2-状态变更
            notification.setTitle("需求状态已变更");
            notification.setContent(content);
            notification.setSenderId(operatorId);
            
            notifications.add(notification);
        }
        
        // 批量插入通知
        return notificationMapper.batchInsert(notifications) > 0;
    }
    
    @Override
    @Transactional
    public boolean sendAssignmentNotification(Long issueId, Long operatorId, Long assigneeId) {
        IssueNotification notification = new IssueNotification();
        notification.setIssueId(issueId);
        notification.setReceiverId(assigneeId);
        notification.setNotificationType(3); // 3-分配
        notification.setTitle("需求已指派给您");
        notification.setContent("有新的需求已指派给您，请查看详情");
        notification.setSenderId(operatorId);
        
        return notificationMapper.insert(notification) > 0;
    }
    
    // 以下是额外的辅助方法
    
    /**
     * 创建通知（内部使用）
     */
    @Transactional
    public IssueNotification createNotification(IssueNotification notification) {
        notification.setCreateTime(LocalDateTime.now());
        notification.setIsRead(0);
        
        notificationMapper.insert(notification);
        return notification;
    }
    
    /**
     * 根据用户ID获取通知列表（内部使用）
     */
    public List<IssueNotification> getNotificationsByUserId(Long userId) {
        return notificationMapper.getNotificationsByUserId(userId);
    }
    
    /**
     * 根据用户ID获取未读通知列表（内部使用）
     */
    public List<IssueNotification> getUnreadNotificationsByUserId(Long userId) {
        return notificationMapper.getUnreadNotificationsByUserId(userId);
    }
    
    /**
     * 根据需求ID获取通知列表（内部使用）
     */
    public List<IssueNotification> getNotificationsByIssueId(Long issueId) {
        return notificationMapper.getNotificationsByIssueId(issueId);
    }
    
    /**
     * 根据类型获取通知列表（内部使用）
     */
    public List<IssueNotification> getNotificationsByType(String type) {
        // 将字符串类型转换为数字
        int typeCode = 1; // 默认为评论
        if ("status_change".equals(type)) {
            typeCode = 2;
        } else if ("assignment".equals(type)) {
            typeCode = 3;
        } else if ("mention".equals(type)) {
            typeCode = 4;
        }
        
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("notificationType", typeCode);
        return notificationMapper.findByConditions(conditions);
    }
    
    /**
     * 根据用户ID获取未读通知数量（内部使用）
     */
    public int getUnreadNotificationCountByUserId(Long userId) {
        return notificationMapper.countUnreadNotificationsByUserId(userId);
    }
    
    /**
     * 批量标记为已读（内部使用）
     */
    @Transactional
    public boolean batchMarkAsRead(Long userId, List<Long> notificationIds) {
        return notificationMapper.batchMarkAsRead(userId, notificationIds) > 0;
    }
    
    /**
     * 标记所有通知为已读（内部使用）
     */
    @Transactional
    public boolean markAllAsReadByUserId(Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("receiverId", userId);
        params.put("isRead", 1);
        params.put("readTime", LocalDateTime.now());
        
        return notificationMapper.batchUpdateByCondition(params) > 0;
    }
    
    /**
     * 删除通知（内部使用）
     */
    @Transactional
    public boolean deleteNotification(Long notificationId) {
        return notificationMapper.deleteById(notificationId) > 0;
    }
    
    /**
     * 删除已读通知（内部使用）
     */
    @Transactional
    public boolean deleteReadNotificationsByUserId(Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("receiverId", userId);
        params.put("isRead", 1);
        
        return notificationMapper.batchDeleteByCondition(params) > 0;
    }
    
    /**
     * 获取最新通知（内部使用）
     */
    public List<IssueNotification> getLatestNotificationsByUserId(Long userId, Integer limit) {
        return notificationMapper.getLatestNotificationsByUserId(userId, limit);
    }
    
    /**
     * 根据时间范围获取通知（内部使用）
     */
    public List<IssueNotification> getNotificationsByTimeRange(Long userId, String startTime, String endTime) {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("receiverId", userId);
        conditions.put("startTime", startTime);
        conditions.put("endTime", endTime);
        
        return notificationMapper.findByConditions(conditions);
    }
    
    /**
     * 创建评论通知（内部使用）
     */
    @Transactional
    public boolean createNotificationsForComment(Long issueId, Long authorId, List<Long> mentionedUserIds, String content) {
        return sendCommentNotification(issueId, authorId, content, mentionedUserIds);
    }
    
    /**
     * 创建状态变更通知（内部使用）
     */
    @Transactional
    public boolean createNotificationsForStatusChange(Long issueId, Long operatorId, Long oldStatusId, Long newStatusId) {
        String oldStatusName = getStatusName(oldStatusId);
        String newStatusName = getStatusName(newStatusId);
        
        // 这里应该获取需求的相关人员（作者、指派人等）来发送通知
        // 为了简化，返回true
        return sendStatusChangeNotification(issueId, operatorId, oldStatusName, newStatusName, new ArrayList<>());
    }
    
    /**
     * 创建分配通知（内部使用）
     */
    @Transactional
    public boolean createNotificationsForAssignment(Long issueId, Long assignerId, Long assigneeId) {
        return sendAssignmentNotification(issueId, assignerId, assigneeId);
    }
    
    /**
     * 获取通知统计（内部使用）
     */
    public Map<String, Object> getNotificationStatsByUserId(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        int totalCount = notificationMapper.countByReceiverId(userId);
        int unreadCount = notificationMapper.countUnreadByReceiverId(userId);
        
        stats.put("totalCount", totalCount);
        stats.put("unreadCount", unreadCount);
        stats.put("readCount", totalCount - unreadCount);
        
        return stats;
    }
    
    /**
     * 根据状态ID获取状态名称
     * 
     * @param statusId 状态ID
     * @return 状态名称
     */
    private String getStatusName(Long statusId) {
        // 这里应该从数据库或缓存中获取状态名称
        // 为了简化，返回默认值
        if (statusId == 1L) {
            return "新建";
        } else if (statusId == 2L) {
            return "进行中";
        } else if (statusId == 3L) {
            return "待审核";
        } else if (statusId == 4L) {
            return "已解决";
        } else {
            return "未知";
        }
    }
}